<template>
  <view class="container">
    <u-navbar
      title="宽带信息登记"
      :autoBack="true"
      :fixed="true"
      :bgColor="'#ffffff'"
      :placeholder="true"
      :titleStyle="{
        color: '#333',
        fontSize: '16px',
      }"></u-navbar>

    <!-- 表单内容 -->
    <view class="form-content">
      <view class="title">
        <view class="line"></view>
        套餐说明
      </view>
      <!-- 区域 -->
      <view class="form-item arrow" @click="selectArea">
        <text class="label required">区/县:</text>

        <input
          class="input"
          v-model="form.area"
          placeholder="请选择区/县"
          disabled
          placeholder-style="color: #999" />
        <!-- <view class="value">{{ form.area || "区域" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showArea"
        :columns="columnsArea"
        @cancel="cancelArea"
        @confirm="confirmArea"
        keyName="name"></u-picker>

      <view class="form-item arrow" @click="selectHouseType">
        <text class="label required">街道</text>
        <input
          class="input"
          v-model="form.street"
          placeholder="请选择街道"
          disabled
          placeholder-style="color: #999" />

        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showHouseType"
        :columns="columnsHouseType"
        @cancel="cancelHouseType"
        @confirm="confirmHouseType"
        keyName="name"></u-picker>

      <view class="form-item arrow" @click="selectContractType">
        <text class="label required">村</text>
        <input
          class="input"
          v-model="form.address"
          placeholder="请选择村"
          disabled
          placeholder-style="color: #999" />

        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showContractType"
        :columns="columnsContractType"
        @cancel="cancelContractType"
        @confirm="confirmContractType"
        keyName="name"></u-picker>

      <!-- 类型 -->
      <view class="form-item arrow" @click="selectType">
        <text class="label required">运营商</text>
        <input
          class="input"
          v-model="form.yunying"
          placeholder="请选择运营商"
          placeholder-style="color: #999"
          disabled />
        <!-- <view class="value">{{  || "整租" }}</view> -->
        <u-icon name="arrow-right" color="#999" size="16"></u-icon>
      </view>
      <u-picker
        :show="showType"
        :columns="columnsType"
        @cancel="cancelType"
        @confirm="confirmType"
        keyName="text"></u-picker>

      <view class="form-item">
        <text class="label required">开户名:</text>
        <input
          class="input"
          type="text"
          v-model="form.name"
          placeholder="请输入开户名"
          placeholder-style="color: #999" />
      </view>
      <view class="form-item">
        <text class="label required">联系电话:</text>
        <input
          class="input"
          type="number"
          v-model="form.mobile"
          placeholder="请输入联系电话"
          placeholder-style="color: #999" />
      </view>
      <view class="form-item">
        <text class="label required">宽带账号:</text>
        <input
          class="input"
          type="number"
          v-model="form.account"
          placeholder="请输入宽带账号"
          placeholder-style="color: #999" />
      </view>
      <view class="form-item">
        <text class="label required">宽带接入地址:</text>
        <input
          class="input"
          type="text"
          v-model="form.acc_address"
          placeholder="请输入宽带接入地址"
          placeholder-style="color: #999" />
      </view>
    </view>
    <view class="form-content">
      <view class="title">
        <view class="line"></view>
        故障问题
      </view>
      <!-- 标签选择 -->
      <view class="tags-section">
        <view class="tags-list">
          <!-- -->
          <view
            :class="{ active: form.selectedTags.includes(tag.id) }"
            class="tag-item"
            v-for="(tag, index) in tags"
            :key="index"
            @click="toggleTag(tag.id)">
            {{ tag.title }}
          </view>
        </view>
      </view>
    </view>
    <view class="form-content">
      <view class="title">
        <view class="line"></view>
        提供办理运营商单据凭证
      </view>
      <view
        class=""
        style="color: #737373; font-size: 24rpx; margin-left: 20rpx">
        (电子单据或受理单据拍照上传即可)
      </view>
      <!-- 图片上传 -->
      <view class="upload-section">
        <view class="upload-content">
          <u-upload
            :fileList="fileList1"
            @afterRead="afterRead"
            @delete="deletePic"
            name="1"
            multiple
            :maxCount="9">
            <view class="upload-item">
              <u-icon name="photo" size="28" color="#0095f8"></u-icon>
              <text>上传图片</text>
            </view>
          </u-upload>
        </view>
      </view>

      <u-modal
        :show="tagshow"
        title="新增标签"
        confirmText="确认"
        cancelText="取消"
        :showCancelButton="true"
        @cancel="tagCancel"
        @confirm="tagConfirm">
        <view class="slot-content">
          <u--input
            placeholder="请输入标签"
            border="surround"
            v-model="tagvalue"></u--input>
        </view>
      </u-modal>
    </view>
    <view
      class="bottom-Box"
      :class="inAnimation.dou ? 'Anim' : ''"
      @animationend="inAnimation.dou = false">
      <view class="cercleNo" v-if="!isAgree" @click="selectAgree" />
      <view class="cercleYes" v-if="isAgree" @click="selectAgree">
        <u-icon name="checkmark" color="#ffffff" size="11" />
      </view>
      <view class="yuedu" @click="selectAgree">我已阅读并同意</view>
      <view class="yonghuxuzhi">
        <view @click="toProtocol">《用户服务协议》</view>
        及
        <view @click="toyinsi">《隐私政策》</view>
      </view>
      <!-- <view class="yinsizhengce" @click="toSecret">《隐私政策》</view> -->
    </view>
    <!-- 提交按钮 -->
    <view class="submit" @click="handleSubmit">提交</view>
  </view>
</template>

<script>
import {
  getyunyingshanglist,
  getquestlist,
  addDengji,
  getquList,
  getjiedaoList,
  getcunList,
} from "@/api/mainapi.js";
const d = new Date();
const year = d.getFullYear();
console.log(year);
let month = d.getMonth() + 1;
month = month < 10 ? `0${month}` : month;
const date = d.getDate();
export default {
  props: ["type"],
  data() {
    return {
      isAgree: false,
      inAnimation: {
        dou: false,
      },
      maxDate: "2099-12-31", // 确保日期格式正确
      minDate: `${year}-${month}-${date}`,
      tabs: ["房屋转租", "便民广告", "商家优惠"],
      video_icon: this.$Config.HTTP_REQUEST_URL + "/img/icon30.png",
      currentTab: 0,
      form: {
        area: "",
        street: "",
        address: "",
        yunying: "",
        name: "",
        mobile: "",
        account: "",
        acc_address: "",
        selectedTags: [],
        yunyingId: "",
        jiedao_id: "",
        qu_id: "",
        village_id: "",
      },
      fileList: [],
      tags: [
        "更换无线路由器，安排上门调试服务",
        "免网费",
        "交通便利",
        "公寓",
        "民房",
        "民用水电",
      ],
      showCalendar: false,
      showHouseType: false,
      showContractType: false,
      showType: false,
      showArea: false,
      columnsHouseType: [[]],
      columnsContractType: [[]],
      columnsType: [[]],
      columnsArea: [[]],
      tagshow: false,
      tagvalue: "",
      fileList1: [],
      fileList2: [],
      videoUrl: "",
    };
  },
  onShow() {
    // const scene = this.getQueryParam("scene");
    // if (scene) {
    //   if (uni.getStorageSync("userInfo") == "") {
    //     uni.navigateTo({
    //       url: "/pages/login/login?scene=2",
    //     });
    //   }
    // }
  },
  onLoad(params) {
    console.log(params);
    if (params.scene) {
      if (uni.getStorageSync("userInfo") == "") {
        uni.navigateTo({
          url: "/pages/login/login?scene=2",
        });
      }
    }
  },
  mounted() {
    this.getyunyingshanglist();
    this.getTagList();
    this.getArea();
    // this.getGent();
    // this.getCun();
  },
  methods: {
    getQueryParam(name) {
      const urlParams = new URLSearchParams(window.location.search);
      return urlParams.get(name);
    },

    async getArea() {
      const res = await getquList();
      if (res.response.statusCode === 200) {
        console.log(res.data.data);
        this.columnsArea = [res.data.data];
      }
    },
    async getGent(v) {
      const res = await getjiedaoList({
        qu_id: v,
      });
      if (res.response.statusCode === 200) {
        this.columnsHouseType = [res.data.data];
      }
    },
    async getCun(v) {
      const res = await getcunList({
        jiedao_id: v,
      });
      if (res.response.statusCode === 200) {
        this.columnsContractType = [res.data.data];
      }
    },
    async getyunyingshanglist() {
      const res = await getyunyingshanglist();
      if (res.response.statusCode === 200) {
        const vueReactiveArray = Object.keys(res.data.data).map((key) => {
          return {
            text: res.data.data[key],
            id: key,
          };
        });
        this.columnsType = [[...vueReactiveArray]];
      }
    },
    selectAgree() {
      this.isAgree = !this.isAgree;
    },
    toyinsi() {
      uni.navigateTo({
        url: "/pages/agreement/index?id=4",
      });
    },
    toProtocol() {
      uni.navigateTo({
        url: "/pages/agreement/index?id=3",
      });
      // wx.openPrivacyContract({
      //   success: () => {
      //     console.log("打开成功");
      //   }, // 打开成功
      //   fail: () => {
      //     uni.showToast({
      //       title: "打开失败，稍后重试",
      //       icon: "none",
      //     });
      //   }, // 打开失败
      // });
    },

    async getTagList() {
      const res = await getquestlist();
      if (res.response.statusCode === 200) {
        this.tags = res.data.data;
      }
    },

    // 删除图片
    deletePic(event) {
      this[`fileList${event.name}`].splice(event.index, 1);
    },
    // 新增图片
    async afterRead(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise(lists[i].url);
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.fullurl,
          })
        );
        fileListLen++;
      }
    }, // 删除视频
    deletePic2() {
      this.fileList2.splice(0, 1);
      this.videoUrl = "";
    },
    // 新增图片
    async afterRead2(event) {
      // 当设置 multiple 为 true 时, file 为数组格式，否则为对象格式
      let lists = [].concat(event.file);
      let fileListLen = this[`fileList${event.name}`].length;
      lists.map((item) => {
        this[`fileList${event.name}`].push({
          ...item,
          status: "uploading",
          message: "上传中",
        });
      });
      for (let i = 0; i < lists.length; i++) {
        const result = await this.uploadFilePromise2(lists[i].url);
        this.videoUrl = result.fullurl;
        let item = this[`fileList${event.name}`][fileListLen];
        this[`fileList${event.name}`].splice(
          fileListLen,
          1,
          Object.assign(item, {
            status: "success",
            message: "",
            url: result.fullurl,
          })
        );
        fileListLen++;
      }
    },
    uploadFilePromise2(url) {
      console.log(url, 234234);
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync("userInfo").token;
        uni.uploadFile({
          url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
          fileType: "all",
          name: "file",
          filePath: url,
          header: {
            token: token,
          },
          success: (res) => {
            console.log(res.data, JSON.parse(res.data).data);
            setTimeout(() => {
              resolve(JSON.parse(res.data).data);
            }, 1000);
          },
        });
      });
    },
    uploadFilePromise(url) {
      return new Promise((resolve, reject) => {
        const token = uni.getStorageSync("userInfo").token;
        uni.compressImage({
          src: url,
          quality: 50,
          success: (chooseImageRes) => {
            uni.uploadFile({
              url: this.$Config.HTTP_REQUEST_URL + "/api/common/upload",
              fileType: "all",
              name: "file",
              filePath: chooseImageRes.tempFilePath,
              header: {
                token: token,
              },
              success: (res) => {
                setTimeout(() => {
                  resolve(JSON.parse(res.data).data);
                }, 1000);
              },
            });
          },
        });
      });
    },

    switchTab(index) {
      this.currentTab = index;
    },
    selectHouseType() {
      // 选择街道
      this.showHouseType = true;
    },
    selectContractType() {
      // 选择村
      this.showContractType = true;
    },
    selectType() {
      // 选择类型
      this.showType = true;
    },
    selectArea() {
      // 选择区域
      this.showArea = true;
    },
    selectLocation() {
      // wgs84 gcj02
      var that = this;
      wx.chooseLocation({
        type: "gcj02",
        success: (res) => {
          console.log(res);
          that.form.location = res.name;
          that.form.latitude = res.latitude;
          that.form.longitude = res.longitude;
        },
      });
    },
    cancelHouseType() {
      this.showHouseType = false;
    },
    confirmHouseType(e) {
      console.log(e);
      this.showHouseType = false;
      this.form.street = e.value[0].name;
      this.form.jiedao_id = e.value[0].id;
      this.form.address = "";
      this.getCun(this.form.jiedao_id);
    },
    cancelContractType() {
      this.showContractType = false;
    },
    confirmContractType(e) {
      this.showContractType = false;
      this.form.address = e.value[0].name;
      this.form.village_id = e.value[0].id;
    },
    cancelType() {
      this.showType = false;
    },
    confirmType(e) {
      this.showType = false;
      this.form.yunying = e.value[0].text;
      this.form.yunyingId = e.value[0].id;
    },
    cancelArea() {
      this.showArea = false;
    },
    confirmArea(e) {
      this.showArea = false;
      this.form.area = e.value[0].name;
      this.form.qu_id = e.value[0].id;
      this.form.street = "";
      this.form.address = "";
      this.getGent(this.form.qu_id);
    },
    confirmCalendar(date) {
      this.form.expireDate = date;
      this.showCalendar = false;
    },

    toggleTag(tag) {
      const index = this.form.selectedTags.indexOf(tag);
      if (index > -1) {
        this.form.selectedTags.splice(index, 1);
      } else {
        this.form.selectedTags.push(tag);
      }
    },
    addNewTag() {
      // 添加新标签
      this.tagshow = true;
    },
    tagCancel() {
      // 添加新标签
      this.tagshow = false;
      this.tagvalue = "";
    },
    tagConfirm() {
      // 添加新标签
      this.tagshow = false;
      if (this.tagvalue != "") {
        this.tags.push(this.tagvalue);
        this.tagvalue = "";
      }
    },
    async handleSubmit() {
      // 提交表单
      if (this.form.area == "") {
        return uni.showToast({
          title: "请选择区",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.street == "") {
        return uni.showToast({
          title: "请选择街道",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.address == "") {
        return uni.showToast({
          title: "请选择村",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.yunying == "") {
        return uni.showToast({
          title: "请选择运营商",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.name == "") {
        return uni.showToast({
          title: "请输入开户名",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.mobile == "") {
        return uni.showToast({
          title: "请输入联系电话",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.account == "") {
        return uni.showToast({
          title: "请输入宽带账号",
          icon: "none",
          duration: 2000,
        });
      }
      if (this.form.acc_address == "") {
        return uni.showToast({
          title: "请输入宽带接入地址",
          icon: "none",
          duration: 2000,
        });
      }
      this.$set(this.inAnimation, "dou", false);
      if (!this.isAgree) {
        uni.showToast({
          title: "请阅读并勾选底部协议",
          icon: "none", //如果要纯文本，不要icon，将值设为'none'
          duration: 1500, //持续时间为 2秒
        });
        // 手机震动
        wx.vibrateShort(
          {
            type: "heavy",
          },
          {
            success: function () {
              // 在成功回调中递归调用自身，以实现震动的连续效果
            },
          }
        );
        return;
      }
      this.inAnimation.dou = true;
      var contcatarr = this.fileList1;
      console.log("提交表单", this.form, this.fileList1);
      var arr = [];
      contcatarr.forEach((element, index) => {
        arr.push(element.url);
      });
      console.log(arr.join(","));
      const res = await addDengji({
        ...this.form,
        question_ids: this.form.selectedTags.join(","),
        yun_image: arr.join(","),
      });
      if (res.response.data.code === 1) {
        uni.showToast({
          title: "提交成功",
          icon: "none",
          duration: 2000,
        });
        // setTimeout(() => {
        //   uni.switchTab({
        //     url: "/pages/index/index",
        //   });
        // }, 1000);
        Object.keys(this.form).forEach((key) => {
          this.form[key] = "";
        });
        this.fileList1 = [];
      }
    },
  },
};
</script>

<style lang="less" scoped>
.container {
  min-height: 100vh;
  background-color: #f5f6fa;
  padding-bottom: constant(safe-area-inset-bottom);
  /* iOS 11.2 */
  padding-bottom: env(safe-area-inset-bottom);
  /* iOS 11.2 */
}

.publish-tip {
  display: flex;
  padding: 20rpx 24rpx;
  font-size: 24rpx;
  color: #999;
  .num {
    color: #ff0000;
  }
}

.form-content {
  width: 92%;
  margin-left: 4%;
  padding: 20rpx 24rpx;
  // height: 778rpx;
  background: #ffffff;
  box-shadow: 0rpx 0rpx 12rpx 0rpx rgba(0, 0, 0, 0.1),
    inset 0rpx 0rpx 0rpx 2rpx #ffffff;
  border-radius: 28rpx;
  margin-top: 20rpx;
  box-sizing: border-box;
  .title {
    display: flex;
    align-items: center;
    font-weight: 500;
    font-size: 32rpx;
    color: #323334;
    .line {
      width: 8rpx;
      height: 32rpx;
      background: #49a1fd;
      margin-right: 10rpx;
    }
  }
  .form-item {
    background: #fff;
    border-radius: 12rpx;
    padding: 24rpx;
    margin-bottom: 24rpx;
    display: flex;
    align-items: center;

    &.arrow {
      padding-right: 24rpx;
    }

    .label {
      font-size: 28rpx;
      color: #333;
      margin-right: 24rpx;

      &.required::before {
        content: "*";
        color: #ff5a5f;
        margin-right: 4rpx;
      }
    }

    .input {
      flex: 1;
      font-size: 28rpx;
      text-align: right;
    }

    .unit {
      font-size: 28rpx;
      color: #999;
      margin-left: 16rpx;
    }

    .value {
      flex: 1;
      font-size: 28rpx;
      color: #333;
      text-align: right;

      &.location {
        color: #2979ff;
      }
    }

    &.textarea {
      padding: 24rpx;
      align-items: flex-start;

      textarea {
        width: 100%;
        height: 200rpx;
        font-size: 28rpx;
      }
    }
  }
}
.submit {
  width: 96%;
  height: 88rpx;
  margin-left: 2%;
  margin-top: 40rpx;
  background: linear-gradient(142deg, #0ca8fd 0%, #4272fa 100%);
  border-radius: 16rpx;
  font-family: PingFangSC, PingFang SC;
  font-weight: 500;
  font-size: 30rpx;
  color: #ffffff;
  line-height: 88rpx;
  text-align: center;
}
.upload-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .upload-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 16rpx;
  }

  .upload-tip {
    font-size: 24rpx;
    color: #999;
    margin-bottom: 24rpx;
  }

  .upload-content {
    display: flex;
    // flex-wrap: wrap;
    // gap: 24rpx;

    .upload-item {
      width: 160rpx;
      height: 160rpx;
      background: #f5f6fa;
      border-radius: 8rpx;
      display: flex;
      flex-direction: column;
      align-items: center;
      justify-content: center;

      text {
        font-size: 24rpx;
        color: #999;
        margin-top: 8rpx;
      }
    }
  }
}

.tags-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .tags-list {
    display: flex;
    flex-wrap: wrap;
    gap: 16rpx;
    margin-bottom: 24rpx;

    .tag-item {
      padding: 12rpx 24rpx;
      font-size: 24rpx;
      color: #666;
      background: #f5f5f5;
      border-radius: 4rpx;

      &.active {
        color: #2979ff;
        background: rgba(41, 121, 255, 0.1);
      }
    }
  }

  .add-tag {
    display: flex;
    align-items: center;
    font-size: 24rpx;
    color: #2979ff;

    text {
      margin-left: 8rpx;
    }
  }
}

.contact-section {
  background: #fff;
  border-radius: 12rpx;
  padding: 24rpx;
  margin-bottom: 24rpx;

  .section-title {
    font-size: 28rpx;
    color: #333;
    margin-bottom: 24rpx;
  }

  .form-item {
    background: none;
    padding: 16rpx 0;
    margin-bottom: 0;
    border-bottom: 2rpx solid #f5f5f5;

    &:last-child {
      border-bottom: none;
    }
  }
}

.submit-btn {
  margin: 0 24rpx;
  height: 88rpx;
  line-height: 88rpx;
  text-align: center;
  background: #2979ff;
  border-radius: 44rpx;
  color: #fff;
  font-size: 32rpx;
}
.bottom-Box {
  display: flex;
  align-items: center;
  width: fit-content;
  margin: 0 auto;
  margin-top: 45rpx;

  &.Anim {
    animation: move 0.1s ease-in-out alternate;
    animation-iteration-count: 5;
    /* 播放两次 */
  }

  .cercleNo {
    width: 30rpx;
    height: 30rpx;
    border-radius: 100%;
    border: 2rpx solid #49a1fd;
  }

  .cercleYes {
    width: 30rpx;
    height: 30rpx;
    border-radius: 100%;
    background-color: #49a1fd;
    display: flex;
    align-items: center;
    justify-content: center;
  }

  .yuedu {
    color: #333333;
    font-size: 28rpx;
    margin-left: 10rpx;
  }

  .yonghuxuzhi {
    color: #49a1fd;
    font-size: 28rpx;
    display: flex;
  }

  .yinsizhengce {
    color: #49a1fd;
    font-size: 28rpx;
  }
}
</style>
